<?php

/**
 * WebUserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class WebUserIdentity extends CUserIdentity
{
	protected $id;
	protected $userModel;
	protected $userName;
	protected $isAdmin = false;

	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		$user = Logins::model()->findByAttributes(array(
			'username' => $this->username
		));
		
		if(!$user){
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		}
		else{
			if($user->password != md5($this->password)){
				$this->errorCode = self::ERROR_PASSWORD_INVALID;
			}
			else{
				$this->errorCode = self::ERROR_NONE;
				$this->id = $user->member_id;
				$this->userModel = $user->Members;
				$this->userName = $user->username;
				
				$user->last_login = date('Y-m-d H:i:s');
				$user->last_login_ip = Yii::app()->request->getUserHostAddress();
				// Update last IP and time
				$user->save();
			}
		}
		return !$this->errorCode;
	}
	
	/**
	 * @return int
	 */
	public function getId(){
		return $this->id;
	}
	
	/**
	 * @return string
	 */
	public function getUserName(){
		return $this->userName;
	}
	
	/**
	 * @return boolean
	 */
	public function getIsAdmin(){
		return $this->isAdmin;
	}
	
	/**
	 * @return Members
	 */
	public function getUserModel(){
		return $this->userModel;
	}
}